const db = require('../models/database');

// 接收事件数据
exports.recordEvent = async (req, res) => {
  try {
    const { event_type, event_data, user_id, session_id, script_source, script_version } = req.body;
    
    if (!event_type) {
      return res.status(400).json({
        success: false,
        message: '事件类型不能为空'
      });
    }
    
    const timestamp = Date.now();
    const result = await db.run(
      `INSERT INTO events (event_type, event_data, timestamp, user_id, session_id, script_source, script_version)
       VALUES (?, ?, ?, ?, ?, ?, ?)`,
      [
        event_type, 
        JSON.stringify(event_data || {}), 
        timestamp, 
        user_id || null, 
        session_id || null,
        script_source || '未知来源',
        script_version || '未知版本'
      ]
    );
    
    res.status(201).json({
      success: true,
      message: '事件记录成功',
      event_id: result.lastID
    });
  } catch (error) {
    console.error('记录事件错误:', error);
    res.status(500).json({
      success: false,
      message: '事件记录失败',
      error: error.message
    });
  }
};


// 获取事件统计数据
exports.getEventStats = async (req, res) => {
  try {
    const { script_source } = req.query;
    
    let whereClause = '';
    let params = [];
    
    if (script_source) {
      whereClause = 'WHERE script_source = ?';
      params.push(script_source);
    }
    
    // 统计各类事件数量（按脚本来源分组）
    const eventCounts = await db.all(`
      SELECT script_source, event_type, COUNT(*) as count 
      FROM events 
      ${whereClause}
      GROUP BY script_source, event_type
    `, params);
    
    // 获取最近一次事件的时间（按脚本来源分组）
    const lastEventTimes = await db.all(`
      SELECT script_source, event_type, MAX(timestamp) as last_timestamp
      FROM events
      ${whereClause}
      GROUP BY script_source, event_type
    `, params);
    
    // 计算事件间平均时间（按脚本来源分组）
    // 注意：SQLite3包不支持窗口函数，所以我们需要用另一种方式计算平均时间
    const avgTimeBetweenEvents = [];
    
    // 对每种事件类型分别查询
    for (const eventType of eventCounts) {
      const events = await db.all(`
        SELECT timestamp
        FROM events
        WHERE script_source = ? AND event_type = ?
        ORDER BY timestamp
      `, [eventType.script_source, eventType.event_type]);
      
      if (events.length > 1) {
        let totalDiff = 0;
        let count = 0;
        
        for (let i = 1; i < events.length; i++) {
          const diff = events[i].timestamp - events[i-1].timestamp;
          totalDiff += diff;
          count++;
        }
        
        const avgDiff = totalDiff / count;
        
        avgTimeBetweenEvents.push({
          script_source: eventType.script_source,
          event_type: eventType.event_type,
          avg_time_diff_ms: avgDiff
        });
      }
    }
    
    res.status(200).json({
      success: true,
      stats: {
        event_counts: eventCounts,
        avg_time_between_events: avgTimeBetweenEvents,
        last_event_times: lastEventTimes.map(item => ({
          script_source: item.script_source,
          event_type: item.event_type,
          last_timestamp: item.last_timestamp,
          formatted_time: new Date(item.last_timestamp).toLocaleString('zh-CN')
        }))
      }
    });
  } catch (error) {
    console.error('获取统计数据错误:', error);
    res.status(500).json({
      success: false,
      message: '获取统计数据失败',
      error: error.message
    });
  }
};

// 获取所有脚本来源列表
exports.getScriptSources = async (req, res) => {
  try {
    const sources = await db.all(`
      SELECT DISTINCT script_source
      FROM events
      ORDER BY script_source
    `);
    
    res.status(200).json({
      success: true,
      sources: sources.map(item => item.script_source)
    });
  } catch (error) {
    console.error('获取脚本来源错误:', error);
    res.status(500).json({
      success: false,
      message: '获取脚本来源失败',
      error: error.message
    });
  }
};
